// 加载模块
let layer = layui.layer;
// 渲染出页面
function slideshow() {
    $.ajax({
        url: 'admin/swipers',
        success: function (res) {
            console.log(res);
            let arr = []
            res.data.forEach(item => {
                let x = '';
                if (item.swiperstatus === 1) {
                    x = `<button id="state"  data-status="1" class="success" data-swiperstatus=${item.swiperstatus} data-id="${item.id}">√</button>`;
                } else if (item.swiperstatus === 2) {
                    x = `<button data-status="2" id="state" data-swiperstatus=${item.swiperstatus} class="loser" data-id="${item.id}">x</button>`;
                }
                arr.push(`<tr>
                <td>${item.id}</td>
                <td><img src="http://localhost:8888/uploads/${item.swiperimg}" alt=""></td>
                <td>${item.swiperimg}</td>
                <td>
                ${x}
                </td>
                <td><button type="button" class="layui-btn  layui-btn-danger layui-btn-xs" data-id="${item.id}">删除</button></td>
              </tr>`)
            })
            $('tbody').html(arr.join(''))
        }
    })
}
slideshow()

// 点击上传后触发点击上传事件
$('#test1').on('click', function () {
    $('#upload').trigger('click')
})


//上传图片

$('body').on('change', '#upload', function (e) {
    let file = e.target.files
    var fd = new FormData()
    // $.each(file, function (index, item) {
    //     fd.append('swipers', item)
    // })
    for (let i = 0; i < file.length; i++) {
        fd.append('swipers', file[i])
    }
    $.ajax({
        data: fd,
        processData: false,
        contentType: false,
        type: 'POST',
        url: 'admin/swipers',
        success: function (res) {
            if (res.status == 0) {
                layer.msg(res.message)
                slideshow()
            }
        }

    })
})
// 点击切换状态
$('body').on('click', '#state', function () {
    let id = $(this).data('id')
    let swiperstatus = $(this).data('swiperstatus')
    if (swiperstatus == 1) {
        swiperstatus = 2
    } else if (swiperstatus == 2) {
        swiperstatus = 1
    }


    $.ajax({
        type: 'PUT',
        url: 'admin/swipers/' + id,
        data: { status: swiperstatus },
        success: function (res) {
            if (res.status == 0) {
                layer.msg(res.message)
                slideshow()
            }

        }
    })
})



// 删除轮播图
$('body').on('click', 'button:contains("删除")', function () {

    let id = $(this).data('id')
    layer.confirm('确定删除?', function (index) {
        //do something
        $.ajax({
            type: 'DELETE',
            url: 'admin/swipers/' + id,
            success: function (res) {
                if (res.status == 0) {
                    layer.msg(res.message)
                    slideshow()
                }
            }
        })

        layer.close(index);
    });

})